<template>
  <div>
    <PageTitleSearch
      :title="title"
      :hotelList="hotelList"
      :currentHotel="currentHotel"
      v-model:lastMonth="lastMonth"
      :currentAcc="currentAcc"
      @hotel-change="handleSelectChange"
      @date-change="handleDateSelect"
      @acc-change="handleAccSelect"
    />
    <div class="main-content">
      <a-row :gutter="12">
        <a-col :span="8">
          <FlexCard title="出租率" :loading="loading" :is-center-title="true">
            <RingImg v-if="rentRateData.length > 0" :dataList="rentRateData" height="300px" />
          </FlexCard>
        </a-col>
        <a-col :span="8">
          <FlexCard title="平均房价" :loading="loading" :is-center-title="true">
            <BarSingleImg v-if="priceData.length > 0" :dataList="priceData" unit="元" height="300px" formatter="dot2Formatter|0" />
          </FlexCard>
        </a-col>
        <a-col :span="8">
          <FlexCard title="每房收益" :loading="loading" :is-center-title="true">
            <BarSingleImg v-if="perData.length > 0" :dataList="perData" unit="元" height="300px" formatter="dot2Formatter|0" />
          </FlexCard>
        </a-col>
      </a-row>

      <a-row :gutter="12" style="margin-top: 15px;s">
        <a-col :span="8">
          <FlexCard title="客房收入" :loading="loading" :is-center-title="true">
            <BarSingleImg v-if="incomeData.length > 0" :dataList="incomeData" unit="万元" height="300px" />
          </FlexCard>
        </a-col>
        <a-col :span="8">
          <FlexCard title="客房利润" :loading="loading" :is-center-title="true">
            <BarSingleImg v-if="gopData.length > 0" :dataList="gopData" unit="万元" height="300px" />
          </FlexCard>
        </a-col>
        <a-col :span="8">
          <FlexCard title="利润率" :loading="loading" :is-center-title="true">
            <RingImg v-if="gopRateData.length > 0" :dataList="gopRateData" height="300px" />
          </FlexCard>
        </a-col>
      </a-row>
    </div>
  </div>
</template>
<script>
  import dayjs from 'dayjs';
  import { defHttp } from '/@/utils/http/axios';
  import * as MathUtil from '/@/utils/MathUtil';
  import * as DateUtil from '/@/utils/dateUtil';
  import * as Constant from '/@/utils/Constant';
  import PageTitleSearch from '@/views/applications/ui/PageTitleSearch.vue';
  import FlexCard from '@/views/applications/ui/FlexCard.vue';
  import RingImg from '@/views/applications/ui/RingImg.vue';
  import BarSingleImg from '@/views/applications/ui/BarSingleImg.vue';

  const COLOR_RED = '#F53F3F';
  const COLOR_GREEN = '#00B42A';
  const COLOR_WARN = '#FDA757';
  const COLOR_BLUE = '#212A7C';
  const COLOR_PURPLE = '#665C99';
  const REPORT_NAME = '酒店月度客房关键数据（项目）';
  const REPORT_CODE = 'hotel-month-single-roomkey';
  const INCOME_APIS = {
    month: 'getHotelMonthRoomKey',
    year: 'getHotelMonthAccRoomKey',
  };

  export default {
    name: REPORT_NAME,

    components: {
      PageTitleSearch,
      FlexCard,
      RingImg,
      BarSingleImg,
    },

    data() {
      return {
        title: '客房部分-客房关键数据',
        reportCode: '',
        reportName: '',
        loading: false,
        tableHigh: { x: '100%', y: 308 },
        lastMonth: dayjs().subtract(1, 'month').format('YYYYMM'),
        hotelList: [],
        accList: [
          { label: '当月', value: 'month' },
          { label: '当年', value: 'year' },
        ],
        currentHotel: {},
        currentAcc: 'month',
        gopList: [],
        priceData: [],
        perData: [],
        incomeData: [],
        rentRateData: [],
        gopRateData: [],
        gopData: [],
      };
    },

    created() {
      defHttp.get({ url: '/data/hotel/list' }, { isTransformResponse: false }).then((res) => {
        if (res.success && res.result.length > 0) {
          this.hotelList = res.result.map((s) => {
            return { label: s.name, value: s.code };
          });
          console.log(this.hotelList);
          const currentHotelCode = this.$route.query.hotelCode || localStorage.getItem(Constant.STORAGE_HOTEL_NAME);
          if (currentHotelCode && res.result.filter((d) => d.code === currentHotelCode).length > 0) {
            this.currentHotel = res.result.filter((d) => d.code === currentHotelCode)[0];
          } else {
            this.currentHotel = {
              code: res.result[0].code,
              name: res.result[0].name,
            };
          }
          this.hotelSel = this.currentHotel;
          const accName = this.accList.filter((a) => a.value === this.currentAcc)[0].label;
          this.reportCode = `${REPORT_CODE}-${this.currentAcc}-${this.currentHotel.code}-${this.lastMonth}`;
          this.reportName = `${REPORT_NAME}-${accName}-${this.currentHotel.name}-${this.lastMonth}`;
          this.fetchData();
        }
      });
    },

    methods: {
      fetchData() {
        this.loading = true;
        defHttp
          .post({
            url: '/data/query',
            data: {
              labelCode: INCOME_APIS[this.currentAcc],
              sqlParams: [
                {
                  key: 'code',
                  value: this.currentHotel.code,
                },
                {
                  key: 'month',
                  value: this.lastMonth,
                },
              ],
              pageIndex: 1,
              pageSize: 100,
            },
          })
          .then((res) => {
            if (res.datas && res.datas.data.length > 0) {
              const dataList = res.datas.data;
              const croom = dataList.filter((i) => i.subjectCode === 'A')[0];
              const sroom = dataList.filter((i) => i.subjectCode === 'B')[0];
              const roomIncome = dataList.filter((i) => i.subjectCode === '0101')[0];
              const roomGop = dataList.filter((i) => i.subjectCode === '0301')[0];
              this.rentRateData = [
                {
                  name: '去年',
                  value: this.safeDivide(sroom.lActual, croom.lActual),
                  color: COLOR_WARN,
                },
                {
                  name: '预算',
                  value: this.safeDivide(sroom.budget, croom.budget),
                  color: COLOR_PURPLE,
                },
                {
                  name: this.currentAcc === 'month' ? '实际' : '年累计',
                  value: this.safeDivide(sroom.actual, croom.actual),
                  color: COLOR_BLUE,
                },
              ];
              this.priceData = [
                {
                  name: this.currentAcc === 'month' ? '实际' : '年累计',
                  value: this.safeDivide(roomIncome.actual, sroom.actual),
                  color: COLOR_BLUE,
                },
                {
                  name: '预算',
                  value: this.safeDivide(roomIncome.budget, sroom.budget),
                  color: COLOR_PURPLE,
                },
                {
                  name: '去年',
                  value: this.safeDivide(roomIncome.lActual, sroom.lActual),
                  color: COLOR_WARN,
                },
              ];
              this.perData = [
                {
                  name: this.currentAcc === 'month' ? '实际' : '年累计',
                  value: this.safeDivide(roomIncome.actual, croom.actual),
                  color: COLOR_BLUE,
                },
                {
                  name: '预算',
                  value: this.safeDivide(roomIncome.budget, croom.budget),
                  color: COLOR_PURPLE,
                },
                {
                  name: '去年',
                  value: this.safeDivide(roomIncome.lActual, croom.lActual),
                  color: COLOR_WARN,
                },
              ];
              this.incomeData = [
                {
                  name: this.currentAcc === 'month' ? '实际' : '年累计',
                  value: roomIncome.actual,
                  color: COLOR_BLUE,
                },
                {
                  name: '预算',
                  value: roomIncome.budget,
                  color: COLOR_PURPLE,
                },
                {
                  name: '去年',
                  value: roomIncome.lActual,
                  color: COLOR_WARN,
                },
              ];
              this.gopData = [
                {
                  name: this.currentAcc === 'month' ? '实际' : '年累计',
                  value: roomGop.actual,
                  color: COLOR_BLUE,
                },
                {
                  name: '预算',
                  value: roomGop.budget,
                  color: COLOR_PURPLE,
                },
                {
                  name: '去年',
                  value: roomGop.lActual,
                  color: COLOR_WARN,
                },
              ];
              this.gopRateData = [
                {
                  name: '去年',
                  value: this.safeDivide(roomGop.lActual, roomIncome.lActual),
                  color: COLOR_WARN,
                },
                {
                  name: '预算',
                  value: this.safeDivide(roomGop.budget, roomIncome.budget),
                  color: COLOR_PURPLE,
                },
                {
                  name: this.currentAcc === 'month' ? '实际' : '年累计',
                  value: this.safeDivide(roomGop.actual, roomIncome.actual),
                  color: COLOR_BLUE,
                },
              ];
            } else {
              this.rentRateData = [];
              this.priceData = [];
              this.perData = [];
              this.incomeData = [];
              this.gopData = [];
              this.gopRateData = [];
            }
            localStorage.setItem(Constant.STORAGE_HOTEL_NAME, this.currentHotel.code);
            this.loading = false;
          });
      },
      getTrianglePoint(point, interval = 5, rise = true) {
        return [
          [point[0], rise ? point[1] - interval : point[1] + interval],
          [point[0] - interval, rise ? point[1] + interval : point[1] - interval],
          [point[0] + interval, rise ? point[1] + interval : point[1] - interval],
        ];
      },
      getBarOption(data) {
        return {
          grid: {
            top: '26%',
            left: '15%',
            right: '15%',
            bottom: '10%',
          },
          tooltip: {
            show: false,
            triggerOn: 'none',
          },
          xAxis: {
            axisLabel: {
              fontWeight: 400,
            },
            data: data.map((i) => i.name),
            axisTick: {
              show: false,
            },
          },
          yAxis: {
            max: 1,
            show: false,
          },
          series: [
            {
              type: 'bar',
              barWidth: 36,
              itemStyle: {
                color: function (params) {
                  // 根据数据索引返回不同颜色
                  const colors = data.map((d) => d.color);
                  return colors[params.dataIndex];
                },
                barBorderRadius: [5, 5, 5, 5],
              },
              data: data.map((d) => d.value),
              label: {
                show: true,
                position: 'top', // 可以设置为'top'、'bottom'、'left'、'right'等显示在不同位置
              },
            },
          ],
          graphic: [
            {
              type: 'text',
              style: {
                text: '单位：元',
                textAlign: 'left',
              },
            },
            {
              type: 'group',
              right: 0,
              children: [
                {
                  type: 'text',
                  right: 20,
                  style: {
                    text: `较${data[1].name}： ${data[0].value - data[1].value}`,
                    textAlign: 'right',
                  },
                },
                {
                  type: 'polygon',
                  right: 5,
                  top: 2,
                  shape: {
                    points: this.getTrianglePoint([0, 0], 4, data[0].value >= data[1].value),
                  },
                  style: {
                    fill: data[0].value >= data[1].value ? COLOR_GREEN : COLOR_RED,
                  },
                },
                {
                  type: 'text',
                  style: {
                    text: this.diffPercent2Formatter(data[0].value, data[1].value, 0),
                    fill: data[0].value >= data[1].value ? COLOR_GREEN : COLOR_RED,
                  },
                },
              ],
            },
            {
              type: 'group',
              right: 0,
              top: 20,
              children: [
                {
                  type: 'text',
                  right: 20,
                  style: {
                    text: `较${data[2].name}： ${data[0].value - data[2].value}`,
                    textAlign: 'right',
                  },
                },
                {
                  type: 'polygon',
                  right: 5,
                  top: 2,
                  shape: {
                    points: this.getTrianglePoint([0, 0], 4, data[0].value >= data[2].value),
                  },
                  style: {
                    fill: data[0].value >= data[2].value ? COLOR_GREEN : COLOR_RED,
                  },
                },
                {
                  type: 'text',
                  style: {
                    text: this.diffPercent2Formatter(data[0].value, data[2].value, 0),
                    fill: data[0].value >= data[2].value ? COLOR_GREEN : COLOR_RED,
                  },
                },
              ],
            },
          ],
        };
      },
      filterOption(input, option) {
        return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
      },
      handleSelectChange(value) {
        this.currentHotel = {
          code: value,
          name: this.hotelList.filter((h) => h.value === value)[0].label,
        };
        const accName = this.accList.filter((a) => a.value === this.currentAcc)[0].label;
        this.reportCode = `${REPORT_CODE}-${this.currentAcc}-${this.currentHotel.code}-${this.lastMonth}`;
        this.reportName = `${REPORT_NAME}-${accName}-${this.currentHotel.name}-${this.lastMonth}`;
        this.fetchData();
      },
      handleAccSelect(value) {
        const name = this.accList.filter((h) => h.value === value)[0].label;
        this.currentAcc = value;
        this.reportCode = `${REPORT_CODE}-${value}-${this.currentHotel.code}-${this.lastMonth}`;
        this.reportName = `${REPORT_NAME}-${name}-${this.currentHotel.name}-${this.lastMonth}`;
        this.fetchData();
      },
      isMonthDisabled(current) {
        const lastMonth = dayjs().subtract(1, 'month');
        return current.isAfter(lastMonth);
      },
      handleDateSelect() {
        const name = this.accList.filter((h) => h.value === this.currentAcc)[0].label;
        this.reportCode = `${REPORT_CODE}-${this.currentAcc}-${this.currentHotel.code}-${this.lastMonth}`;
        this.reportName = `${REPORT_NAME}-${name}-${this.currentHotel.name}-${this.lastMonth}`;
        this.fetchData();
      },
      handleDataChange(val) {
        this.dateSel = val;
      },
      showFilterPopup() {
        this.filterPopup = true;
        this.dateSel = this.currentDate;
      },
      cancelFilter() {
        this.filterPopup = false;
      },
      confirmFilter() {
        this.currentDate = this.dateSel;
        this.fetchData();
        this.filterPopup = false;
      },
      currencyWFormatter(value, dot = 2, unit = '万') {
        return MathUtil.currencyWFormatter(value, dot, unit);
      },
      currencyWNFormatter(value, dot = 0) {
        return MathUtil.currencyWNFormatter(value, dot);
      },
      currencyWNDFormatter(value, dot = 0) {
        return MathUtil.currencyWNDFormatter(value, dot);
      },
      percent2DFormatter(value, dot = 2) {
        return MathUtil.percent2DFormatter(value, dot);
      },
      diffPercent2Formatter(thisData, lastData, dot = 2) {
        return MathUtil.diffPercent2Formatter(thisData, lastData, dot);
      },
      dot2Formatter(value, dot = 2) {
        return MathUtil.dot2Formatter(value, dot);
      },
      dateRangeFormatter(dataRange) {
        return DateUtil.dateRangeFormatter(dataRange);
      },
      dateFormatter(data) {
        return DateUtil.dateFormatter(data);
      },
      monthFormatter(data) {
        return DateUtil.monthFormatter(data);
      },
      safeDivide(numerator, denominator) {
        return MathUtil.safeDivide(numerator, denominator);
      },
    },
  };
</script>

<style lang="less" scoped>
  .main-frame-header {
    display: flex;
    top: 0;
    width: 100%;
    height: 63px;
    background-color: #112c4d;
    box-shadow: 0 1px 3px hsla(0, 0%, 0%, 0.3);
    z-index: 1000;
    align-items: center;
    justify-content: center;
  }

  .main-frame-title {
    color: #ffffff;
    font-size: 18px;
    font-weight: 500;
  }

  .main-frame-header-container {
    display: -webkit-flex;
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: inherit;
  }

  .main-frame-header-start {
    flex: 1 1 auto;
    display: -webkit-flex;
    display: flex;
    justify-content: flex-start;
  }

  .main-frame-header-center {
    display: flex;
    flex-direction: column;
    text-align: center;
  }

  .main-frame-remark {
    color: #ffffff;
    font-size: 12px;
    margin-top: 3px;
  }

  .main-frame-header-end {
    flex: 1 1 auto;
    display: -webkit-flex;
    display: flex;
    justify-content: flex-end;
  }

  .main-frame-header-item {
    flex: 0 0 auto;
    margin: 0 8px 0 8px;
  }

  .main-content {
    padding: 12px 0;

    &-title {
      &-custom {
        color: #00b578;
      }
    }
  }

  .card-double {
    display: flex;
    margin: 12px 0 12px 0;
    justify-content: space-between;

    &-item {
      flex-basis: 48%;
    }
  }

  .interval-area {
    margin-bottom: 12px;
  }

  .select-title-space {
    width: 200px;
    margin-right: 20px;
  }

  ::v-deep .select-title .van-cell {
    color: hsl(217, 16%, 60%);
    font-size: 0.875rem;
    line-height: 1.25rem;
    padding: unset;
    -webkit-box-pack: end;
    -ms-flex-pack: end;
    justify-content: flex-end;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    position: relative;
    background-color: #112c4d;
  }

  .popup-right {
    width: auto;

    &-content {
      height: 800px;
      width: 318px;

      &-oprate {
        display: flex;
        padding: 16px;
        justify-content: center;

        &-item {
          width: 100%;
          margin-right: 10px;
        }

        &-item:last-child {
          margin-right: 0;
        }
      }
    }
  }

  @media @desktop {
    .row-content {
      display: flex;
    }
    .card-flex-all {
      flex: 1 1 calc(100% - 10px);
    }
    .card-flex {
      flex: 1 1 calc(50% - 10px);
    }
    .card-flex-70 {
      flex: 1 1 calc(66% - 10px);
    }
    .card-flex-30 {
      flex: 1 1 calc(33% - 10px);
    }
    .card-flex-60 {
      flex: 1 1 calc(60% - 10px);
    }
    .card-flex-40 {
      flex: 1 1 calc(40% - 10px);
    }

    .card-in-flex {
      display: flex;
    }


    .echarts {
      width: 100%;
      height: 300px;
    }

    .card-in-flex-30 {
      flex: 1;
    }

    .card-in-flex-70 {
      flex: 2;
    }

    .row-left {
      flex: 4;
    }
    .row-right {
      flex: 1;
    }
    .flex-height {
      height: 96%;
    }

    .remark-card {
      min-height: 200px;
    }
  }
</style>
